import { defineConfig, loadEnv } from 'vite';
import path from 'node:path';
import uni from '@dcloudio/vite-plugin-uni';
import UniPages from '@uni-helper/vite-plugin-uni-pages';
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts';
import AutoImport from 'unplugin-auto-import/vite';
import { WotResolver } from '@uni-helper/vite-plugin-uni-components/resolvers';
import ViteRestart from 'vite-plugin-restart';
import Components from '@uni-helper/vite-plugin-uni-components';
import fs from 'fs';
import scssVarsPlugin from './plugin/vite-plugin-scss-vars';
import vitePluginDirectives from './plugin/vite-plugin-directives';
import { getVariables } from './src/theme/themeVars';
// 读取 subpackage.json
let subPackages = [];
try {
  const subpackageContent = fs.readFileSync(path.resolve(process.cwd(), 'subpackage.json'), 'utf-8');
  const subpackageData = JSON.parse(subpackageContent);
  subPackages = subpackageData.subPackages || [];
} catch (error) {
  console.warn('Failed to load subpackage.json:', error);
}

export default async ({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const UnoCSS = (await import('unocss/vite')).default;
  const { VITE_DELETE_CONSOLE, VITE_SHOW_SOURCEMAP } = env;
  const platform = process.env.UNI_PLATFORM;

  return defineConfig({
    server: {
      port: 8999 // 设置默认端口号为 8999，你可以根据需求修改
    },
    plugins: [
      vitePluginDirectives({
        directives: 'v-perms' // 自定义指令名称（默认：v-perms）
      }),
      UniPages({
        exclude: ['**/components/**/**.*'], // 排除的文件
        routeBlockLang: 'json5', // 虽然设了默认值，但是vue文件还是要加上 lang="json5", 这样才能很好地格式化
        // homePage 通过 vue 文件的 route-block 的type="home"来设定
        // pages 目录为 src/pages，分包目录不能配置在pages目录下
        subPackages, // 是个数组，可以配置多个，但是不能为pages里面的目录
        dts: 'src/types/uni-pages.d.ts' // 生成的类型文件，默认是 src/types/uni-pages.d.ts
      }),
      UniLayouts(),
      Components({
        resolvers: [WotResolver()]
      }),
      AutoImport({
        imports: [
          'vue',
          'uni-app',
          {
            from: 'uni-mini-router',
            imports: ['createRouter', 'useRouter', 'useRoute']
          }
        ],
        dts: 'src/types/auto-import.d.ts',
        eslintrc: { enabled: true, globalsPropValue: true },
        vueTemplate: true,
        dirs: ['src/hooks'] // 自动导入 hooks
      }),
      UnoCSS(),
      uni(),
      scssVarsPlugin({
        outputPath: 'src/static/styles/generated-vars.scss',
        getVariables: getVariables
      }),
      ViteRestart({
        restart: ['vite.config.ts']
      })
    ],
    resolve: {
      alias: {
        '@': path.join(process.cwd(), './src'),
        '@img': path.join(process.cwd(), './src/static'),
        '~': path.join(process.cwd(), './')
      }
    },
    optimizeDeps: {
      exclude: process.env.UNI_PLATFORM === 'h5' && process.env.NODE_ENV === 'development' ? ['wot-design-uni'] : []
    },
    build: {
      sourcemap: VITE_SHOW_SOURCEMAP === 'true',
      target: 'es6',
      minify: mode === 'development' ? false : 'terser',
      terserOptions: {
        compress: {
          drop_console: VITE_DELETE_CONSOLE === 'true',
          drop_debugger: true
        }
      }
    },
    define: {
      'process.env': {}
    }
  });
};
